package cn.com.gift.config;

import cn.com.gift.dto.LoginUserInfo;
import cn.com.gift.utils.GlobalVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * Copyright (C), 2018-2024
 * FileName: LoginUserInterceptor
 * Author:   Mr
 * Date:     2024/6/11 19:10
 * Description:
 */
@Component
public class LoginUserInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUserInfo loginUser = GlobalVariable.getLoginUser(request);
        if (loginUser != null ) {
            if (loginUser.getLoginTime().plusMinutes(30).isAfter(LocalDateTime.now())) {
                loginUser.setLoginTime(LocalDateTime.now());
                GlobalVariable.putLoginUser(request, loginUser);
                return true;
            } else {
                GlobalVariable.removeLoginUser(request);
            }
        }
        response.setStatus(401);
        return false;
    }
}
